
// Copyright (C) 2011 Luca Piccioni
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//  
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

using Derm.Render;
using Derm.Xml;
using Derm.Xml.Collada;

namespace Derm.Scene
{
	/// <summary>
	/// Graph node type.
	/// </summary>
	public enum RenderGraphNodeType
	{
		/// <summary>
		/// Node dedicated only for transforming the model stack.
		/// </summary>
		TransformNode,
		/// <summary>
		/// Node dedicated only for rendering a single RenderObject.
		/// </summary>
		ObjectNode,
		/// <summary>
		/// Node dedicated only for keeping track of a point of view.
		/// </summary>
		CameraNode,
		/// <summary>
		/// Node dedicated only for keeping track of a light.
		/// </summary>
		LightNode,
		/// <summary>
		/// Node dedicated only for rendering a single RenderObject, choosen by a set.
		/// </summary>
		SwitchObjectNode,
	}

	/// <summary>
	/// Graph node dedicated for rendering.
	/// </summary>
	/// <remarks>
	/// </remarks>
	public abstract class RenderGraphNode : DirectedGraphNode<RenderGraphNode>, IXmlSerializableExt
	{
		#region Constructors

		/// <summary>
		/// Construct a RenderGraphNode.
		/// </summary>
		protected RenderGraphNode()
		{
			// By default, graph node has a transform state
			State.DefineState(new TransformState());
		}

		/// <summary>
		/// Construct a RenderGraphNode.
		/// </summary>
		/// <param name="identifier">
		/// A <see cref="System.String"/> that identifies this graph node.
		/// </param>
		protected RenderGraphNode(string identifier) : this()
		{
			mIdentifier = identifier;
		}

		#endregion

		#region Render Node Identifier and Type

		/// <summary>
		/// Get or set RenderGraphNode identifier.
		/// </summary>
		public string Identifier
		{
			get { return (mIdentifier); }
			set { mIdentifier = value; }
		}

		/// <summary>
		/// Get the type of this RenderGraphNode.
		/// </summary>
		public abstract RenderGraphNodeType NodeType { get; }

		/// <summary>
		/// This RenderGraphNode identifier.
		/// </summary>
		[XmlAttribute(AttributeName="Identifier", Namespace=XmlHelper.DermNamespace)]
		private string mIdentifier = String.Empty;

		#endregion

		#region Render State

		/// <summary>
		/// Node model transformation respect the parent node.
		/// </summary>
		public ModelMatrix LocalModel
		{
			get {
				return State.IsDefinedState(TransformState.StateId) ? (((TransformState)State[TransformState.StateId]).LocalModel) : (ModelMatrix.Identity);
			}
		}

		/// <summary>
		/// Node model transformation respect the root node.
		/// </summary>
		public virtual ModelMatrix WorldModel
		{
			get
			{
				Stack<ModelMatrix> modelStack = new Stack<ModelMatrix>();
				RenderGraphNode cursor = this;
				ModelMatrix worldModel = new ModelMatrix();

				while (cursor != null) {
					// Store local model
					modelStack.Push(cursor.LocalModel);
					// Go to parent, if any
					cursor = cursor.Parent;
				}

				modelStack.Pop();
				while (modelStack.Count > 0)
					worldModel = worldModel * modelStack.Pop();

				return (worldModel);
			}
		}

		/// <summary>
		/// Node model transformation respect the root node.
		/// </summary>
		public virtual ModelMatrix WorldViewModel
		{
			get
			{
				Stack<ModelMatrix> modelStack = new Stack<ModelMatrix>();
				RenderGraphNode cursor = this;
				ModelMatrix worldModel = new ModelMatrix();

				while (cursor != null) {
					// Store local model
					modelStack.Push(cursor.LocalModel);
					// Go to parent, if any
					cursor = cursor.Parent;
				}

				while (modelStack.Count > 0)
					worldModel = worldModel * modelStack.Pop();

				return (worldModel);
			}
		}

		/// <summary>
		/// The render state for this graph node.
		/// </summary>
		public readonly RenderStateSet State = new RenderStateSet();

		#endregion

		#region Rendering

		/// <summary>
		/// Render this graph node hierarchy.
		/// </summary>
		/// <param name="ctx">
		/// A <see cref="RenderContext"/> used for drawing this node.
		/// </param>
		public virtual void Render(RenderContext ctx)
		{
			if (ctx == null)
				throw new ArgumentNullException("ctx");

			// Apply this node state, and do not alter parent node state
			ctx.PushState();
			ctx.ApplyState(State);

			// Render this node
			RenderThisNode(ctx);

			// Restore inherited state from parent when state is not inheritable
			// ...

			// Render every children
			foreach (RenderGraphNode child in Children)
				child.Render(ctx);

			ctx.PopState();
		}

		/// <summary>
		/// Render only this node.
		/// </summary>
		/// <param name="ctx">
		/// A <see cref="RenderContext"/> used for drawing this node.
		/// </param>
		protected virtual void RenderThisNode(RenderContext ctx)
		{
			
		}

		#endregion

		#region Culling

		/// <summary>
		/// Renderable culling function.
		/// </summary>
		public enum CullFunct
		{
			/// <summary>
			/// False cull test function.
			/// </summary>
			/// <remarks>
			/// The Renderable will never be culled. It will always rendered. This is the default Renderable
			/// cull test function.
			/// </remarks>
			False,
			/// <summary>
			/// True cull test function.
			/// </summary>
			/// <remarks>
			/// The Renderable will always be culled. It will never be rendered.
			/// </remarks>
			True,
			/// <summary>
			/// Occlusion query cull test function.
			/// </summary>
			/// <remarks>
			/// The Renderable will be culled if the occlusion query determine whether the rendering doesn't
			/// produce pixel fragments. To use this cull function, the RenderContext capabilities must declare
			/// that the extension GL_ARB_occlusion_query is implemented.
			/// </remarks>
			Occlusion
		}
		
		/// <summary>
		/// Determine Renderable culling state (including hierarchy).
		/// </summary>
		/// <param name="window"></param>
		/// <param name="ctx"></param>
		/// <remarks>
		/// This routine is responsible of the culling of this Renderable, and indirectly of
		/// the hierarchy starting from this Renderable. It execute a cull test on this Renderable,
		/// and if the cull test is passed execute the same test of the Renderable children.
		/// 
		/// If the cull test hasn't passed, the Renderable won't be rendered, hiding also its
		/// hierarchy. This is crucial, since the parent cull test determine the visibility of
		/// its all entire hierarchy.
		/// </remarks>
		public void Cull(RenderWindow window, RenderContext ctx)
		{
			
		}
		
		/// <summary>
		/// Determine  this Renderable culling state whenever possible.
		/// </summary>
		private void CullThis()
		{
			CullThis(null, null);
		}
		
		/// <summary>
		/// Determine  this Renderable culling state.
		/// </summary>
		/// <param name="window">
		/// A <see cref="RenderWindow"/>
		/// </param>
		/// <param name="ctx">
		/// A <see cref="RenderContext"/>
		/// </param>
		protected virtual void CullThis(RenderWindow window, RenderContext ctx)
		{
			switch (mCullFunct) {
				case CullFunct.False:
					mCulled = false;
					break;
				case CullFunct.True:
					mCulled = true;
					break;
				case CullFunct.Occlusion:
					// Occlusion query performed before/during rendering
					break;
				default:
					break;	
			}
		}

		/// <summary>
		/// Determine this Renderable culling state.
		/// </summary>
		/// <returns></returns>
		public bool IsCulled
		{
			get {
				return (mCulled);
			}
		}
		
		/// <summary>
		/// Culling function of this Renderable. 
		/// </summary>
		/// <remarks>
		/// 
		/// </remarks>
		public CullFunct CullFunction
		{
			get {
				return (mCullFunct);
			}
			set {
				// Store cull function
				mCullFunct = value;
				// Execute culling immediately, if possible
				CullThis();
			}
		}

		/// <summary>
		/// Renderable cull test function.
		/// </summary>
		/// <remarks>
		/// Initially this Renderable is never culled.
		/// </remarks>
		private CullFunct mCullFunct = CullFunct.False;

		/// <summary>
		/// Renderable cull test result.
		/// </summary>
		/// <remarks>
		/// Initially this Renderable is not culled.
		/// </remarks>
		bool mCulled = false;

		#endregion

		#region IXmlSerializableExt Overrides

		/// <summary>
		/// This property is reserved, apply the System.Xml.Serialization.XmlSchemaProviderAttribute to the class instead.
		/// </summary>
		/// <returns>
		/// An System.Xml.Schema.XmlSchema that describes the XML representation of the object that is produced by the
		/// System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter) method and consumed by the
		/// System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader) method.
		/// </returns>
		public XmlSchema GetSchema() { return (null); }

		/// <summary>
		/// Generates an object from its XML representation.
		/// </summary>
		/// <param name="xmlReader">
		/// The System.Xml.XmlReader stream from which the object is deserialized.
		/// </param>
		public virtual void ReadXml(XmlReader xmlReader)
		{
			XmlHelper.ReadXml(xmlReader, this);
		}

		/// <summary>
		/// Converts an object into its XML representation.
		/// </summary>
		/// <param name="writer">
		/// The System.Xml.XmlWriter stream to which the object is serialized.
		/// </param>
		public void WriteXml(XmlWriter writer)
		{
			
		}

		/// <summary>
		/// Read the attribute of the current XML serializable.
		/// </summary>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading element attributes.
		/// </param>
		public virtual void ReadAttributes(XmlReader xmlReader)
		{
			if (xmlReader == null)
				throw new ArgumentNullException("xmlReader");

			System.Diagnostics.Debug.Assert(xmlReader[XmlAttributeIdentifier] != null);

			// Identifier
			mIdentifier = xmlReader[XmlAttributeIdentifier];
		}

		/// <summary>
		/// Read an element of the current XML serializable.
		/// </summary>
		/// <param name="elementName">
		/// A <see cref="System.String"/> that specify the element name.
		/// </param>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading child element.
		/// </param>
		public virtual void ReadElement(string elementName, XmlReader xmlReader)
		{
			if (elementName == null)
				throw new ArgumentNullException("elementName");
			if (xmlReader == null)
				throw new ArgumentNullException("xmlReader");
		}

		/// <summary>
		/// Read the text of the current XML serializable.
		/// </summary>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading child element. It is positioned at the start element.
		/// </param>
		public void ReadText(XmlReader xmlReader)
		{
			
		}

		/// <summary>
		/// Name of the 'sXmlNameCurrentView' attribute that specify the currently selected view identifier.
		/// </summary>
		private const string XmlAttributeIdentifier = "Identifier";

		/// <summary>
		/// Name of the element that specify the children nodes.
		/// </summary>
		private const string XmlElementLocalModel = "LocalModel";

		/// <summary>
		/// Name of the element that specify the children nodes.
		/// </summary>
		private const string XmlElementRenderStateSet = "RenderStateSet";

		/// <summary>
		/// Name of the element that specify the children nodes.
		/// </summary>
		private const string XmlElementNodesNode = "Nodes";

		#endregion
	}
}